# /user/bin/python3
# -*- coding: utf-8 -*-

# ----- txt2npy.py -----

import numpy as np
import os

root = "../datas/"

# 读取邻接矩阵文件获取节点数
adj_matrix_path = root + "adj_matrix.txt"
with open(adj_matrix_path, "r") as f:
    node_num = int(f.readline().strip())  # 读取第一行作为节点数

print(f"检测到节点数: {node_num}")

# 计算三维矩阵的总元素数量
total_elements = (node_num + 1) ** 3  # 包含索引0到node_num

# 读取二进制文件
bin_path = root + "D_bin.txt"
with open(bin_path, "rb") as f:
    raw_data = f.read()

# 验证数据长度
if len(raw_data) != total_elements:
    raise ValueError(
        f"文件大小不匹配! 预期 {total_elements} 字节, 实际 {len(raw_data)} 字节"
    )

# 转换为 numpy 数组
dist_array = np.frombuffer(raw_data, dtype=np.uint8)  # 每个值为 0-255 的无符号字节

# 重塑为三维矩阵 (node_num+1, node_num+1, node_num+1)
dist_3d = dist_array.reshape((node_num + 1, node_num + 1, node_num + 1))

# 保存为 .npy 文件
npy_path = root + "D_bin.npy"
np.save(npy_path, dist_3d)

print(f"转换完成! 文件已保存至: {npy_path}")
print(f"矩阵形状: {dist_3d.shape} (node_num+1, node_num+1, node_num+1)")
